package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.to.SociaUser;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.common.vo.MemberRespVo;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 */
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    RestTemplate restTemplate;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {

        //https://api.weibo.com/oauth2/access_token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&code=CODE
//        String url = "https://api.weibo.com/oauth2/access_token";
        String url = "https://api.weibo.com/oauth2/access_token?client_id=1909313385&client_secret=63b285ce64563556e6294fc5fe840a16&grant_type=authorization_code&redirect_uri=http://auth.gulimall.com/oauth2.0/weibo/success&code="
                + code;
//        Map<String, String> map = new LinkedMultiValueMap();
//        map.put("client_id", "1909313385");
//        map.put("client_secret", "63b285ce64563556e6294fc5fe840a16");
//        map.put("grant_type", "authorization_code");
//        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
//        map.put("code", code);
        //1、根据code换取accessToken
        ResponseEntity<SociaUser> responseEntity = restTemplate.postForEntity(url, null, SociaUser.class);
//        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2.0/access_token", "post", null, null, map);
        //2、处理换取结果
        if (responseEntity.getStatusCodeValue() == 200) {
            //成功获取到accessToken
//            String s = responseEntity.getEntity().toString();
//            SociaUser sociaUser = JSON.parseObject(s, SociaUser.class);
            SociaUser sociaUser = responseEntity.getBody();

            //2）、如果用户是第一次进入网站，自动注册(为当前用户生成一个会员信息账号，以后这个社交账号就对应这个会员账号)
            //远程调用->社交登录或注册
            R r = memberFeignService.oauthlogin(sociaUser);
            if (r.getCode() == 0) {
                MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
                });
                //TODO 已解决1、默认发的JSESSIONID，作用域:当前域。（解决子域session共享问题）
                //TODO 已解决2、使用JSON序列化方式，将session数据序列化到redis中。
                session.setAttribute("loginUser", data);
                //成功登录就返回首页
                return "redirect:http://gulimall.com";
            } else {
                //社交登录不正确，重回登录页面
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            //社交登录不正确，重回登录页面
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }


}
